<template>
  <Form class="xtx-form" :validation-schema="veeSchema" v-slot="{errors}" ref="formCom">
    <div class="user-info">
      <img src="@/assets/images/loading.gif" alt="" v-if="!QQUserInfo.figureurl_1">
      <img v-else :src="QQUserInfo.figureurl_1" alt="" />
      <p>Hi，{{QQUserInfo.nickname}} 欢迎来小兔鲜，完成绑定后可以QQ账号一键登录哦~</p>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :class="{err:errors.mobile}" name='mobile' v-model="form.mobile" class="input" type="text" placeholder="绑定的手机号" />
      </div>
      <div class="error">{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :class="{err:errors.code}" name='code' v-model="form.code" class="input" type="text" placeholder="短信验证码" />
        <span class="code" @click="sendCode">{{time?`等待${time}秒`:'发送验证码'}}</span>
      </div>
      <div class="error">{{errors.code}}</div>
    </div>
    <a href="javascript:;" class="submit"  @click="login">立即绑定</a>
  </Form>
</template>

<script>
import veeSchema from '@/utils/vee-validate-schema'
import { Form, Field } from 'vee-validate'
import { userQQBindCode, userQQBindLogin } from '@/api/user'
import { inject, onUnmounted, reactive, ref } from 'vue'
import { useIntervalFn } from '@vueuse/core'
import Message from '@/components/library/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackBind',
  components: { Form, Field },
  setup () {
    const QQUserInfo = inject('QQUserInfo')
    const formCom = ref(null)
    const form = reactive({
      mobile: null,
      code: null
    })
    // 单独的抽出计时器
    const time = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, { immediate: false })
    // 组件卸载时清除定时器
    onUnmounted(() => {
      pause()
    })
    // 点击发送验证码
    const sendCode = async () => {
      if (time.value !== 0) return
      // 验证手机号
      const codeRes = veeSchema.mobile(form.mobile)
      if (codeRes === true) {
        try {
          await userQQBindCode(form.mobile)
          time.value = 60
          resume()
        } catch (error) {
          Message({ type: 'error', text: error.response.data.message })
        }
      } else formCom.value.setFieldError('mobile', codeRes)
    }
    const store = useStore()
    const router = useRouter()
    // 点击立即绑定按钮
    const login = async () => {
      const valid = await formCom.value.validate()
      if (valid && QQUserInfo.value.openId) {
        try {
          const { result } = await userQQBindLogin({ unionId: QQUserInfo.value.openId, mobile: form.mobile, code: form.code })
          store.commit('user/setUser', result)
          router.push(store.state.user.redirectUrl)
          Message({ type: 'success', text: '登录成功' })
        } catch (error) {
          Message({ type: 'error', text: error.response.data.message })
        }
      }
    }
    return { QQUserInfo, sendCode, formCom, veeSchema, form, time, login }
  }
}
</script>

<style scoped lang='less'>
.user-info {
    width: 320px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    background: #f2f2f2;
    align-items: center;
    padding: 0 10px;
    margin-bottom: 25px;
    img {
      background: #f2f2f2;
      width: 50px;
      height: 50px;
    }
    p {
      padding-left: 10px;
    }
  }
  .code {
    position: absolute;
    right: 0;
    top: 0;
    line-height: 50px;
    width: 80px;
    color: #999;
    &:hover {
      cursor: pointer;
    }
  }
</style>
